package org.communicationSystem;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @ClassName CommuncationServer
 * @Description TODO
 * @Author director吴
 * @Date 2022/1/6 13:15
 * @Version 1.0
 **/
public class CommuncationServer {

    private Selector selector;
    private ServerSocketChannel listenChannel;
    private final int PORT = 6666;


    public CommuncationServer(){
        try {
            selector =   Selector.open();   //初始化选择器
            listenChannel= ServerSocketChannel.open(); //获取服务器 ServerSocketChannel
            listenChannel.socket().bind(new InetSocketAddress(PORT)); //绑定端口
            listenChannel.configureBlocking(false); // 设置非阻塞模式
            listenChannel.register(selector, SelectionKey.OP_ACCEPT); //注册到selector
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public void listen() {
        try {

            while (true) {
                int count = selector.select();
                if (count > 0) {
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {

                        SelectionKey key = iterator.next();

                        //判断监听事件
                        if (key.isAcceptable()) {
                            SocketChannel acceptChannel = listenChannel.accept();
                            //从serversocketChannel中获取客户端的  socketChannl
                            acceptChannel.register(selector, SelectionKey.OP_READ);
                            acceptChannel.configureBlocking(false);//注册到selector
                            System.out.println("客户端" + acceptChannel.getRemoteAddress()+ "--连接");
                        }


                        if (key.isReadable()) {

                        }

                        iterator.remove();


                    }
                } else {
                    System.out.println("监听中。。。");
                }
            }
        } catch (Exception e) {

        }
    }








}
